<template>
  <div>
    <div v-if="searchStatus" class="box-shadow pad10 mgb10">
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="fnmb">
        <div class="flex jbetween">
          <div>
            <el-form-item label="编号">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="名称">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </div>
          <div class="flex fnw jend acenter">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <MyTable
      :tableList="tableList"
      :total="Total"
      :columns="columns"
      v-model:page="page"
      v-model:searchStatus="searchStatus"
      :btnList="$checkBtn(['ExecutionPlan:edit', 'ExecutionPlan:delete'])"
      @getList="getList"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <template v-slot:tabTop>
        <el-button
          type="primary"
          v-hasPermi="['ExecutionPlan:add']"
          icon="CirclePlusFilled"
          @click="handleAdd"
          >添加方案</el-button
        >
        <el-button
          type="primary"
          v-hasPermi="['ExecutionPlan:set']"
          @click="$router.push('/ExecutionPlanItem')"
          >执行项配置</el-button
        >
      </template>
    </MyTable>
    <MyDialog
      v-model:show="show"
      :title="title"
      :formRef="formRef"
      :width="1000"
      @confirm="confirm"
    >
      <el-form :model="formData" :rules="rules" inline ref="formRef">
        <el-form-item label="方案编号" prop="Code">
          <el-input v-model="formData.Code" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="方案名称" prop="Name">
          <el-input v-model="formData.Name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="备注" prop="Remark">
          <el-input
            v-model="formData.Remark"
            type="textarea"
            placeholder="请输入"
            clearable
            autosize
          />
        </el-form-item>

        <MyTable
          v-model:tableList="showSelectList"
          :total="selectTotal"
          :columns="selectColumns"
          :btnList="['delete']"
          v-model:page="selectPage"
          :toolbar="false"
          :searchStatus="false"
          @delete="selectDelete"
          height="500"
        >
          <template v-slot:tabTop>
            <el-button type="primary" @click="bindExecution"
              >选择执行项</el-button
            >
          </template>
        </MyTable>
      </el-form>
    </MyDialog>
    <MyDialog
      v-model:show="bindDialog"
      :title="bindTitle"
      @confirm="subConfirm"
    >
      <ItemList
        :searchStatus="false"
        v-model:selectList="selectList"
      ></ItemList>
    </MyDialog>
  </div>
</template>

<script setup name="ExecutionPlan">
import { ref, getCurrentInstance, onMounted } from "vue";
import ItemList from "@/views/sixManage/ExecutionPlan/itemList";
import {
  AddSixSalePlan,
  EditSixSalePlan,
  DelSixSalePlan,
  GetSixSalePlanList_Page,
  GetSixSalePlanDetail,
} from "@/api/sixManage/executionPlan.js";

const { proxy } = getCurrentInstance();
const tableList = ref([]);
const Total = ref(0);
const columns = ref([
  { label: "序号" },
  { label: "编号", prop: "Code" },
  { label: "名称", prop: "Name" },
  { label: "备注", prop: "Remark" },
  { label: "创建时间", prop: "CreateTime" },
  { label: "创建人", prop: "CreateUser", user: true },
  { label: "修改时间", prop: "UpdateTime" },
  { label: "修改人", prop: "UpdateUser", user: true },
  { label: "操作", width: 160 },
]);

const selectColumns = ref([
  { label: "序号" },
  { label: "编号", prop: "Code", width: 160 },
  { label: "内容", prop: "Content" },
  { label: "排序", prop: "Sort", inputNum: true, width: 180 },
  { label: "操作", width: 100 },
]);

proxy.$formatKey(columns.value);
proxy.$formatKey(selectColumns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10,
});
const selectPage = ref({
  PageIndex: 1,
  PageSize: 10,
});
const searchStatus = ref(true);
const queryParams = ref({
  Code: "",
  Name: "",
  NoPage: "", //如果传"true"，则返回全部数据不分页
});
const queryRef = ref();
const show = ref(false);
const title = ref();
const formRef = ref();
const rules = ref({
  Code: [{ required: true, message: "请输入", trigger: "blur" }],
  Name: [{ required: true, message: "请输入", trigger: "blur" }],
  Principal: [{ required: true, message: "请选择", trigger: "change" }],
});
const formData = ref({});
const selectList = ref([]);
const bindDialog = ref(false);
const bindTitle = ref("");
const selectTotal = ref(0);
const showSelectList = ref([]);
onMounted(() => {
  getList();
});

async function getList() {
  try {
    show.value = false;
    let query = {
      ...queryParams.value,
      ...page.value,
    };
    let res = await GetSixSalePlanList_Page(query);
    tableList.value = res.data.List;
    Total.value = res.data.Total;
    selectList.value = tableList.Items;
  } catch (error) {
    console.log(error);
  }
}

function bindExecution() {
  bindTitle.value = "绑定执行项";
  bindDialog.value = true;
}

async function confirm(val) {
  try {
    if (val) {
      let query = {
        ...formData.value,
        Items: showSelectList.value?.map((item) => {
          return {
            ID_Items: item.ID, //执行项ID
            Sort: item.Sort, //排序
          };
        }),
      };
      if (formData.value.ID) {
        await EditSixSalePlan(query);
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await AddSixSalePlan(query);
        proxy.$modal.msgSuccess("添加成功");
      }

      getList();
    }
  } catch (error) {
    console.log(error);
  }
}

function subConfirm() {
  // selectTotal.value = selectList.value.length;
  showSelectList.value = selectList.value;
  bindDialog.value = false;
}

function selectDelete(row) {
  selectList.value = selectList.value?.filter((item) => item.ID != row.ID);
  showSelectList.value = showSelectList.value?.filter(
    (item) => item.ID != row.ID
  );
}

async function handleEdit(row) {
  try {
    let { data } = await GetSixSalePlanDetail({ ID: row.ID });
    formData.value = {
      Code: data.Info.Code,
      Name: data.Info.Name,
      Remark: data.Info.Remark,
      ID: data.Info.ID,
    };
    data.Items?.forEach((item) => {
      item.ID = item.ID_Items;
    });
    showSelectList.value = data.Items;
    selectList.value = showSelectList.value;
    title.value = "修改执行方案";
    show.value = true;
  } catch (error) {
    console.log(error);
  }
}
async function handleDelete(row) {
  try {
    await DelSixSalePlan({ ID: row.ID });
    proxy.$modal.msgSuccess("删除成功");
    getList();
  } catch (error) {
    console.log(error);
  }
}
function handleAdd() {
  show.value = true;
  formData.value = {};
  showSelectList.value = [];
  selectList.value = [];
  title.value = "添加执行方案";
}
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Code: "",
    Name: "",
    NoPage: "",
  };
  handleQuery();
}
</script>

<style lang="scss" scoped>
.selectBox {
  display: flex;
  border: 1px solid #ddd;
  margin-bottom: 10px;
  .selectItem {
    padding: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
